package com.lzy.content;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.lzy.model.AliyunContentScanResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 阿里云内容测试服务
 *
 * @author lzy
 */
@Slf4j
public class AliyunContentDetect {

    private final DefaultAcsClient client;


    /**
     * 纯文本内容校验
     *
     * @param content 文内容
     */
    public AliyunContentScanResult detectTextContent(String... content) {
        TextScanRequest request = createDefaultTextScanRequest();
        request.setHttpContent(new Gson().toJson(contentData(content)).getBytes(StandardCharsets.UTF_8), "UTF-8", FormatType.JSON);
        try {
            HttpResponse response = client.doAction(request);
            return new Gson().fromJson(new String(response.getHttpContent(), StandardCharsets.UTF_8), AliyunContentScanResult.class);
        } catch (Exception e) {
            log.error("文本内容检测失败!", e);
            AliyunContentScanResult aliyunContentScanResult = new AliyunContentScanResult();
            aliyunContentScanResult.setCode(500);
            return aliyunContentScanResult;
        }
    }


    public AliyunContentDetect(DefaultAcsClient client, DefaultProfile profile) {
        this.client = client;
    }

    /**
     * 创建请求体
     *
     * @param content 待检测的内容
     * @return
     */
    private Map<String, Object> contentData(String... content) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("scenes", Collections.singletonList("antispam"));
        map.put("tasks", contentTask(content));
        return map;
    }

    /**
     * 将所有内容分割成执行任务
     *
     * @param content 内容
     * @return
     */
    private List<Map<String, String>> contentTask(String... content) {
        return Stream.of(content)
                .flatMap(o -> split(o).stream())
                .filter(o -> !StringUtils.isEmpty(o))
                .map(o -> {
                    Map<String, String> map = new HashMap<>(2);
                    map.put("id", UUID.randomUUID().toString().replaceAll("-", ""));
                    map.put("content", o);
                    return map;
                }).collect(Collectors.toList());
    }

    /**
     * 正则分割字符串
     *
     * @param str str
     * @return
     */
    private List<String> split(String str) {
        String pattern = "[\\S,\\s]{9000}";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        List<String> stringList = new ArrayList<>();
        int index = 0;
        while (m.find()) {
            stringList.add(m.group());
            index++;
        }
        stringList.add(str.substring(index * 4));
        return stringList;
    }

    /**
     * 构建默认请求
     *
     * @return
     */
    private TextScanRequest createDefaultTextScanRequest() {
        TextScanRequest textScanRequest = new TextScanRequest();
        // 指定API返回格式。
        textScanRequest.setAcceptFormat(FormatType.JSON);
        textScanRequest.setHttpContentType(FormatType.JSON);
        // 指定请求方法。
        textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST);
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId("cn-shanghai");
        textScanRequest.setConnectTimeout(3000);
        textScanRequest.setReadTimeout(6000);
        return textScanRequest;
    }
}
